<template>
  <div class="content">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="loginForm" :model="param" :rules="rules" ref="login">
          <h1 class="titleTest">Hello</h1>
          <h2 class="titleTest">欢迎使用&nbsp;👏</h2>
          <el-form-item prop="username">
            <el-input placeholder="请输入账号" class="enput" :prefix-icon="User" v-model="param.username" clearable
              @keyup.enter="submitForm(login)">

            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" placeholder="请输入密码" :prefix-icon="Lock" class="enput" v-model="param.password"
              show-password clearable @keyup.enter="submitForm(login)">

            </el-input>
          </el-form-item>
          <el-form-item prop="weiCode">
            <el-input placeholder="请输入验证码" class="enput-code" v-model="param.weiCode" maxlength="4" clearable
              @keyup.enter="submitForm(login)">

            </el-input>
            <canvas id="captchaCanvas"></canvas>
          </el-form-item>
          <el-form-item>
            <el-button :disabled="btnLoading" color="#f8d852" size="default" class="login-btn" @click="submitForm(login)">
              登&nbsp;&nbsp;录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { reqLogin } from '@/api/user/index'
import { ElMessage, ElNotification } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock } from "@element-plus/icons-vue";
import { whatTime } from '@/utils/plugins'
// import useUseStore from '@/store/modules/user'
const router = useRouter()
// const useStore = useUseStore()

let weiCode = ''
const btnLoading = ref(false)

interface LoginInfo {
  username: string
  password: string
  weiCode: string
}

const param = reactive<LoginInfo>({
  username: 'wei',
  password: 'admin',
  weiCode: ''
})

const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  weiCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const login = ref<FormInstance>()
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (valid) {
      if (
        param.weiCode.toLowerCase() != weiCode.toLowerCase() ||
        param.weiCode.toUpperCase() != weiCode.toUpperCase()
      ) {
        param.weiCode = ''
        // generateCaptcha()
        generateSingleDigitCaptcha()
        ElMessage.error('验证码不正确')
        return
      }
      const params = {
        username: param.username,
        password: param.password
      }
      btnLoading.value = true
      reqLogin(params).then((res: any) => {
        if (res.code == '200') {
          sessionStorage.setItem('token', res.data.token)
          btnLoading.value = false
          router.push('/')
          ElNotification({
            type: 'success',
            message: '欢迎回来 👏',
            title: `Hi~ ${whatTime()}好`
          })
        } else {
          btnLoading.value = false
          // ElMessage.error(res.data.message)
          ElNotification({
            type: 'error',
            message: res.data.message
          })
          param.username = ''
          param.password = ''
          param.weiCode = ''
          // generateCaptcha()
          generateSingleDigitCaptcha()
        }
      })
    }
  })
}

// 随机字母验证码
function generateCaptcha() {
  const canvas = document.getElementById('captchaCanvas') as HTMLCanvasElement
  const context = canvas.getContext('2d') as CanvasRenderingContext2D

  // Set canvas dimensions
  canvas.width = 100
  canvas.height = 50

  // Generate random code
  let code = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (let i = 0; i < 4; i++) {
    code += characters.charAt(Math.floor(Math.random() * characters.length))
  }
  weiCode = code
  // Draw background
  context.fillStyle = '#fff'
  context.fillRect(0, 0, canvas.width, canvas.height)

  // Draw random lines
  for (let i = 0; i < 10; i++) {
    context.beginPath()
    context.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    context.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    context.strokeStyle = '#333'
    context.stroke()
  }

  // Draw random dots
  for (let i = 0; i < 50; i++) {
    context.beginPath()
    context.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
    context.fillStyle = '#000'
    context.fill()
  }

  // Draw code
  context.font = '30px Arial'
  context.fillStyle = '#333'
  for (var i = 0; i < code.length; i++) {
    var x = 10 + i * 18
    var y = 30 + Math.random() * 10 - 5
    var angle = Math.random() * 0.4 - 0.2
    context.save()
    context.translate(x, y)
    context.rotate(angle)
    context.fillText(code.charAt(i), 0, 0)
    context.restore()
  }
  canvas.addEventListener('click', generateCaptcha)
}

// 加减法验证码
function generateSingleDigitCaptcha() {
  const canvas = document.getElementById('captchaCanvas') as HTMLCanvasElement
  const context = canvas.getContext('2d') as CanvasRenderingContext2D
  canvas.addEventListener('click', generateSingleDigitCaptcha)
  // Set canvas dimensions
  canvas.width = 100
  canvas.height = 45

  // Generate random operands and operator
  const operands = [
    Math.floor(Math.random() * 10),
    Math.floor(Math.random() * 10),
  ]
  // const operators = ['+', '-', '*', '/']
  const operators = ['+']
  const operator = operators[Math.floor(Math.random() * operators.length)]

  // Calculate answer
  let answer: number = operands[0] + operands[1]
  // switch (operator) {
  //   case '+':
  //     answer = operands[0] + operands[1]
  //     break
  //   case '-':
  //     answer = operands[0] - operands[1]
  //     break
  //   case '*':
  //     answer = operands[0] * operands[1]
  //     break
  //   case '/':
  //     answer = operands[0] / operands[1]
  //     break
  // }

  // Draw background
  context.fillStyle = '#fff'
  context.fillRect(0, 0, canvas.width, canvas.height)

  // Draw operands and operator
  context.font = 'bold 30px Arial'
  context.fillStyle = '#000'
  context.fillText(
    `${operands[0]}${operator}${operands[1]} = ?`,
    Math.random() * 20,
    Math.random() * 45 + 15
  )

  // Draw random dots
  for (let i = 0; i < 50; i++) {
    context.beginPath()
    context.arc(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      1,
      0,
      2 * Math.PI
    )
    context.fillStyle = '#000'
    context.fill()
  }

  // Set global variable for captcha answer
  weiCode = answer.toString()
}

onMounted(() => {
  // generateCaptcha()
  generateSingleDigitCaptcha()
})

</script>

<style lang="scss" scoped>
.content {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url(@/assets/imgs/new-bg.jpg);
  background-size: cover;

  .loginForm {
    border-radius: 8px;
    padding: 20px 40px 30px;
    background: rgba(0, 0, 0, 0.5);
    position: absolute;
    width: 60vh;
    right: 20vh;
    top: 25vh;
    box-shadow: 0px 3px 20px 0px #e0e6ff;
  }

  .titleTest {
    font-size: 22px;
    font-weight: 500;
    color: #fff;
    margin-top: 20px;
    margin-bottom: 10px;
  }

  .enput {
    width: 100%;
    height: 50px;
    margin-top: 18px;
  }

  .enput-code {
    width: 65%;
    height: 50px;
    margin-top: 25px;
  }

  .login-btn {
    width: 100%;
    height: 50px;
    color: #fff;
    font-size: 20px;
    font-weight: 500;
    text-align: center;
    margin-top: 30px;
  }

  #captchaCanvas {
    padding-top: 23px;
    margin-left: 10px;
  }

  :deep(.el-input__wrapper) {
    background-color: rgba(0, 0, 0, 0.5);
  }

  :deep(.el-input__inner) {
    background-color: rgba(0, 0, 0, 0.5);
  }
}</style>